package com.yj.auto.plugin.license;

import java.io.File;

import com.xiaoleilu.hutool.io.FileUtil;
import com.yj.auto.utils.NetUtil;

public class LicenseTools {
	public static void main(String[] args) throws Exception {
		String path = "d://temp//license.dat";
		licByMac(null, NetUtil.getLocalMacAddress(), path);
		System.out.println(verifyByMac(path));
	}

	public static AutoLicense loadLic(String licPath) throws Exception {
		byte[] bytes = FileUtil.readBytes(new File(licPath));
		if (null == bytes || bytes.length < 1)
			return null;
		String str = new String(bytes);
		String[] ss = str.split(";");
		if (ss.length != 2)
			return null;
		AutoLicense lic = new AutoLicense(ss[0].getBytes(), ss[1].getBytes());
		return lic;
	}

	public static File saveLic(String licPath, String sign) throws Exception {
		if (null == sign)
			return null;
		File file = new File(licPath);
		FileUtil.writeBytes(sign.toString().getBytes(), file);
		return file;
	}

	public static File licByMac(String seed, String text, String licPath) throws Exception {
		AutoLicense lic = getLic(seed, text);
		File file = new File(licPath);
		FileUtil.writeBytes(lic.getText().getBytes(), file);
		return file;
	}

	public static AutoLicense getLic(String seed, String text) throws Exception {
		AutoLicense lic = new AutoLicense();
		lic.generaterKey();
		lic.sign(text);
		return lic;
	}

	public static boolean verifyByMac() throws Exception {
		return verifyByMac(getDefaultLicPath());
	}

	public static boolean verifyByMac(String licPath) throws Exception {
		AutoLicense lic = loadLic(licPath);
		return verifyByMac(lic);
	}

	public static boolean verifyByMac(AutoLicense lic) throws Exception {
		if (null == lic)
			return false;
		String[] macs = NetUtil.getAllMAC();
		for (String mac : macs) {
			if (lic.verify(mac)) {
				return true;
			}
		}
		return false;
	}

	public static boolean verify(String licPath, String text) throws Exception {
		AutoLicense lic = loadLic(licPath);
		if (null == lic)
			return false;
		return lic.verify(text);
	}

	public static String getDefaultLicPath() {
		String path = Thread.currentThread().getContextClassLoader().getResource("/").getPath() + "license.dat";
		return path;
	}
}
